package com.ikas.ai.utils;

import cn.hutool.core.thread.ThreadUtil;
import lombok.extern.slf4j.Slf4j;

import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.ScheduledFuture;
import java.util.concurrent.TimeUnit;

/**
 * AsyncUtil
 *
 * @author lv.yi
 */
@Slf4j
public final class AsyncUtil {

    private static final ScheduledExecutorService POOL = ThreadUtil.createScheduledExecutor(20);

    private AsyncUtil() {
    }

    public static void call(Runnable runnable) {
        POOL.execute(() -> {
            try {
                runnable.run();
            } catch (Exception e) {
                log.error("Async Running Error", e);
            }
        });
    }

    public static ScheduledFuture<?> timer(Runnable runnable, long period) {
        return POOL.scheduleAtFixedRate(() -> {
            try {
                runnable.run();
            } catch (Exception e) {
                log.error("Async Running Error", e);
            }
        }, 0, period, TimeUnit.MILLISECONDS);
    }

}
